package com.szgz.platform.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szgz.platform.model.Task;
import com.szgz.platform.result.ApiResponse;
import com.szgz.platform.result.PageResult;
import com.szgz.platform.service.TaskService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/tasks")
@CrossOrigin(origins = "*")
public class TaskController {

	private final TaskService taskService;

	public TaskController(TaskService taskService) {
		this.taskService = taskService;
	}

	@PostMapping
	public ApiResponse<Task> create(@RequestBody Task task) {
		return ApiResponse.success(taskService.create(task));
	}

	@PutMapping("/{taskId}")
	public ApiResponse<Task> update(@PathVariable String taskId, @RequestBody Task task) {
		task.setTaskId(taskId);
		return ApiResponse.success(taskService.update(task));
	}

	@DeleteMapping("/{taskId}")
	public ApiResponse<Void> delete(@PathVariable String taskId) {
		return taskService.delete(taskId) ? ApiResponse.success() : ApiResponse.fail(404, "Task not found");
	}

	@GetMapping("/{taskId}")
	public ApiResponse<Task> getById(@PathVariable String taskId) {
		Task t = taskService.getById(taskId);
		return t != null ? ApiResponse.success(t) : ApiResponse.fail(404, "Task not found");
	}

	@GetMapping
	public ApiResponse<PageResult<Task>> page(@RequestParam(defaultValue = "1") long pageNum,
	                                         @RequestParam(defaultValue = "10") long pageSize,
	                                         @RequestParam(required = false) String keyword,
	                                         @RequestParam(required = false) String status,
	                                         @RequestParam(required = false) String type,
	                                         @RequestParam(required = false) String difficulty) {
		Page<Task> page = taskService.page(pageNum, pageSize, keyword, status, type, difficulty);
		return ApiResponse.success(PageResult.from(page));
	}
}

